 //
//  CategroyListViewController.m
//  FoodCorner
//
//  Created by Summer on 16/3/2.
//  Copyright © 2016年 Summer. All rights reserved.
//

#import "CategroyListViewController.h"
#import "CookDataHelper.h"
#import "HomeListCell.h"
#import "CategoryModel.h"
#import "FoodPracticeViewController.h"
#import "HomeListViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import <SDAutoLayout/UITableView+SDAutoTableViewCellHeight.h>
@interface CategroyListViewController ()
@property (nonatomic,assign) NSInteger currtent;
@property (nonatomic,strong) UISwipeGestureRecognizer *leftSwipe;
@end
static NSString *identifier = @"cellID";
@implementation CategroyListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[HomeListCell class] forCellReuseIdentifier:identifier];
    [self refreshDataWithFooter];
    //[self refreshDataWithHeader];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemStop) target:self action:@selector(clickBackButtonAciotn)];
    self.leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(clickBackButtonAciotn)];
    _leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self viewBlurEffect];
    [self relodData];
    [self.tableView reloadData];
    
}
- (void)clickBackButtonAciotn
{
    [CookDataHelper shareCookDataHelper].CategoryArray = nil;
    [self.navigationController popViewControllerAnimated:YES];
 }

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return [[CookDataHelper shareCookDataHelper] numberOfDatas];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    CategoryModel * model = [[CookDataHelper shareCookDataHelper] modelOfIndex:indexPath.row];
    cell.categoryModel = model;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodPracticeViewController *foodVC = [[FoodPracticeViewController alloc]init];
    CategoryModel * model = [[CookDataHelper shareCookDataHelper] modelOfIndex:indexPath.row];
    foodVC.categoryModel = model;
    
    [self.navigationController pushViewController:foodVC animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    CategoryModel * model = [[CookDataHelper shareCookDataHelper] modelOfIndex:indexPath.row];
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[HomeListCell class] contentViewWidth:[self cellContentViewWith]];
}
- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 9.2) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

#pragma mark -------加载数据。实现刷新
/**
 *  @author Summer
 *
 *  加载数据
 */
- (void)relodData
{
    [[CookDataHelper shareCookDataHelper] downLoadDataWithNumberOfString:self.categroy andPage:0 success:^{
        [self.tableView reloadData];
    } failed:^(NSString *massage) {
        [self reloadDataFailed:massage];
    }];
}
/**
 *  @author Summer
 *
 *  下拉刷新，实现数据的刷新
 */
- (void)refreshDataWithHeader
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithPullDownHeader)];
    
    // 设置文字
    [header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
    [header setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
    [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
    
    // 设置字体
    header.stateLabel.font = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    
    // 设置颜色
    header.stateLabel.textColor = [UIColor redColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
    
    // 马上进入刷新状态
    [header beginRefreshing];
    
    // 设置刷新控件
    self.tableView.mj_header = header;
}
/**
 *  @author Summer
 *
 *  下拉刷新，方法实现
 */
- (void)refreshDataWithPullDownHeader
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        [self.tableView.mj_header endRefreshing];
    });
    /*
    //    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    progressHUD.mode = MBProgressHUDModeDeterminate;
    //    progressHUD.labelText = @"Loading....";
    //    progressHUD.labelColor = [UIColor redColor];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [progressHUD hide:YES];
    //    });
     */
    
}
/**
 *  @author Summer
 *
 *  上拉刷新，实现数据的更新
 */
- (void)refreshDataWithFooter
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithPullUpFooter)];
    
    // 设置文字
    [footer setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
    [footer setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
    [footer setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
    
    // 设置字体
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    // 设置颜色
    footer.stateLabel.textColor = [UIColor redColor];
    // 马上进入刷新状态
    [footer beginRefreshing];
    
    // 设置刷新控件
    self.tableView.mj_footer = footer;
}
/**
 *  @author Summer
 *
 *  上拉刷新，方法实现
 */
- (void)refreshDataWithPullUpFooter
{
    _currtent += 2;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[CookDataHelper shareCookDataHelper] downLoadDataWithNumberOfString:self.categroy andPage:_currtent success:^{
            [self.tableView reloadData];
        } failed:^(NSString *massage) {
            [self reloadDataFailed:massage];
        }];
    });
    
}
///当刷新数组失败的时候
- (void)reloadDataFailed:(NSString *)massage
{
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
    progressHUD.labelText = [NSString stringWithFormat:@"请求失败错误%@",massage];
    progressHUD.animationType = MBProgressHUDAnimationFade;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [progressHUD hide:YES];
    });
    
}
#pragma mark---- 轮播图代理方法实现
/*
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self reloadImage];
    self.shufflingView.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width , 0);
    
    self.shufflingView.pageControl.currentPage = _shufflingView.currentImageIndex;
}
-(void)reloadImage
{
    CGPoint offset = self.shufflingView.scrollView.contentOffset;
    
    if (offset.x > [UIScreen mainScreen].bounds.size.width) {
        self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    }else if (offset.x <[UIScreen mainScreen].bounds.size.width)
    {
        self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + (int)(self.shufflingView.ImgArray.count -1)) % (self.shufflingView.ImgArray.count);
    }
    
    int leftImageIndex,rightImageIndex;
    
    self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    
    [self.shufflingView.centerImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[self.shufflingView.currentImageIndex]]];
    
    rightImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    leftImageIndex = (self.shufflingView.currentImageIndex + (int)(self.shufflingView.ImgArray.count -1)) % (self.shufflingView.ImgArray.count);
    
    [_shufflingView.leftImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[leftImageIndex]]];
    // NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.ImgArray[rightImageIndex]]];
    
    [_shufflingView.rightImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[rightImageIndex]]];
    
    self.shufflingView.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width , 0);
    
    self.shufflingView.pageControl.currentPage = _shufflingView.currentImageIndex;
    
}
*/
#pragma mark ----添加视图模糊效果，增加视觉效果
- (void)viewBlurEffect
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"placeholder"];
    //毛玻璃效果
    UIVisualEffectView *visualView =[[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:(UIBlurEffectStyleLight)]];
    visualView.alpha = 0.9;
    visualView.frame=[UIScreen mainScreen].bounds;
    
    [imageView addSubview:visualView];
    
    self.tableView.backgroundView = imageView;
    
    self.tableView.separatorEffect = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
}

@end
